package vip.ola.code.secruity;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import vip.ola.core.common.util.DateUtil;
import vip.ola.core.entity.code.CodeUser;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static vip.ola.core.common.constant.CodeConstant.CODE_CODE_SUB_TYPE;
import static vip.ola.core.common.constant.Constant.CODE_ROLE_NORMAL;

public final class JwtUserFactory {

    private JwtUserFactory() {
    }

    public static JwtUser create(String userName, CodeUser codeUser) {
        return new JwtUser(
                codeUser.getId(),
                codeUser.getCodeBusId(),
                codeUser.getAgentId(),
                codeUser.getUsername(),
                codeUser.getType(),
                codeUser.getStatus(),
                userName,
                codeUser.getPassword(),
                codeUser.getEmail(),
                mapToGrantedAuthorities(CODE_ROLE_NORMAL),
                DateUtil.localDateTime2Date(codeUser.getLastPasswordResetTime())
        );
    }

    private static List<GrantedAuthority> mapToGrantedAuthorities(String role) {
        String[] roles = role.split(":");
        List<String> authorities = Arrays.asList(roles);
        return authorities.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }
}